import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';

class SignInController extends GetxController with GetSingleTickerProviderStateMixin {
  /// 响应式成员变量
  final _isPhone = false.obs;

  set isPhone(value) => _isPhone.value = value;

  get isPhone => _isPhone.value;

  final _isObscured = true.obs;

  set isObscured(value) => _isObscured.value = value;

  get isObscured => _isObscured.value;

  final _hasText = false.obs;

  set hasText(value) => _hasText.value = value;

  get hasText => _hasText.value;

  /// 成员变量
  // tab 页标题
  late final List<String> tabTitles;
  late final TabController tabController;

  late String dialCode;
  late final TextEditingController accountController;
  late final TextEditingController passwordController;

  final GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: <String>[
      'email',
      'https://www.googleapis.com/auth/contacts.readonly',
    ],
  );

  Future<void> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? user = await _googleSignIn.signIn();
      if (user != null) {
        Loading.show();
        await Request().post('/google/authLogin', {
          'userId': user.id,
          'nickName': user.displayName,
          'avatar': user.photoUrl,
          'email': user.email,
        }).then((result) {
          UserStore.to.saveProfile(UserLoginResponseEntity.fromJson(result['result']));
          Get.offNamed(Get.parameters['then'] ?? Routes.HOME);
          //TODO 不知为啥Playground没刷新，这里先通知刷新一下，待修复
          EventService.to.sendMessage(EventService.EventRefresh);
        });
      } else {
        Loading.showError('Sign in failed'.tr);
      }
    } catch (error) {
      Loading.showError('Sign in failed'.tr);
      Get.log(error.toString());
    }
  }

  Future<void> signIn() async {
    if (accountController.text.isEmpty) {
      toast('Phone or email empty'.tr);
      return;
    }
    if (tabController.index == 0 && !duIsEmail(accountController.text)) {
      toast('Bad email format'.tr);
      return;
    }
    if (passwordController.text.isEmpty) {
      toast('Password empty'.tr);
      return;
    }
    Loading.show();
    await Request()
        .post(
      '/user/login',
      {
        'email': accountController.text,
        'mobile': accountController.text,
        'mobileType': dialCode,
        'password': passwordController.text,
      }..removeWhere((key, value) =>
          (tabController.index == 1 && key == 'email') || // tab 1 只能输入 mobile
          (tabController.index == 0 && (key == 'mobile' || key == 'mobileType'))), // tab 0 只能输入 email
    )
        .then((result) {
      UserStore.to.saveProfile(UserLoginResponseEntity.fromJson(result['result']));
      Get.offNamed(Get.parameters['then'] ?? Routes.HOME);
      //TODO 不知为啥Playground没刷新，这里先通知刷新一下，待修复
      EventService.to.sendMessage(EventService.EventRefresh);
    });
  }

  /// 生命周期
  @override
  Future<void> onInit() async {
    super.onInit();
    // 准备一些静态数据
    tabTitles = ['Email'.tr, 'Phone number'.tr];
    tabController = TabController(length: tabTitles.length, vsync: this)
      ..addListener(() {
        isPhone = tabController.index == 1;
        accountController.clear();
        Get.focusScope?.unfocus();
      });

    dialCode = ConfigStore.to.countryCode;
    accountController = TextEditingController();
    passwordController = TextEditingController();
  }
}
